//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.mdiy.tag;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.core.Environment;
import freemarker.core._MiscTemplateException;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import java.io.IOException;
import java.util.Map;
import net.mingsoft.config.MSProperties;
import net.mingsoft.mdiy.util.ParserUtil;

public class IncludeExTag implements TemplateDirectiveModel {
    private static final String TEMPLATE_KEY = "template";
    protected static BeansWrapper build;
    private String basePath;
    private StringTemplateLoader stringLoader;

    public IncludeExTag(String basePath, StringTemplateLoader stringLoader) {
        this.basePath = basePath;
        this.stringLoader = stringLoader;
    }

    public void execute(Environment environment, Map params, TemplateModel[] templateModel, TemplateDirectiveBody directiveBody) throws TemplateException, IOException {
        TemplateLoader templateLoader = environment.getConfiguration().getTemplateLoader();
        String uploadTemplatePath = MSProperties.upload.template;
        String path = build.unwrap((TemplateModel)params.get(uploadTemplatePath)).toString();
        if (!params.containsKey(uploadTemplatePath)) {
            throw new MalformedTemplateNameException("missing required parameter '" + uploadTemplatePath, "'");
        } else if (templateLoader.findTemplateSource(path) == null) {
            throw new _MiscTemplateException(environment, "Missing template file path:" + path);
        } else {
            String temp = FileUtil.readString(FileUtil.file(this.basePath, path).getPath(), CharsetUtil.CHARSET_UTF_8);
            temp = ParserUtil.replaceTag(temp);
            this.stringLoader.putTemplate("ms:custom:" + path, temp);
            Template template = environment.getTemplateForInclusion("ms:custom:" + path, (String)null, true);
            environment.include(template);
        }
    }

    static {
        build = (new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)).build();
    }
}
